package com.watson.todolist;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.watson.todolist.constants.DatabaseConstants;
import com.watson.todolist.database.AccountManager;
import com.watson.todolist.database.DatabaseManager;
import com.watson.todolist.database.ToDoListManager;
import com.watson.todolist.to.TodoItem;
import com.watson.todolist.to.TodoListAccount;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

/**
 * This class handles the main screen view which displays todo items and other
 * features to manipulate todo list
 * 
 * @author Donnie Ward
 * 
 * @since 1.0
 * 
 */
public class todoListActivity extends ListActivity {
	
	private long currentRowId;
	private List<TodoItem> todoItemList;
	private ImageView currentCheckBox;
	private static String TAG = "todoListActivity Class";
	private RelativeLayout relativeLayout;
	

	/**
	 * This method is called when the activity is created.
	 * 
	 * @param savedInstanceState
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.todolistlayout);
		
		 todoItemList = new ArrayList<TodoItem>();
		
		populateTodoList();

		Button menuButtonMain = (Button) findViewById(R.id.menuButtonMain);
		Button menuButtonAdd = (Button) findViewById(R.id.menuButtonAdd);
		Button menuButtonSearch = (Button) findViewById(R.id.menuButtonSearch);
		Button menuButtonSettings = (Button) findViewById(R.id.menuButtonSettings);

		// change background image of main to do list menu button (current
		// screen)
		menuButtonMain.setBackgroundResource(R.drawable.menu_main_);

		// Set up search todo button listener
		menuButtonSearch.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(v.getContext(), SearchTodoList.class);
				startActivity(intent);
			}
		});

		// Set up create todo item button listener
		menuButtonAdd.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(v.getContext(), AddTodoItem.class);
				startActivity(intent);
			}
		});

		// Set up settings button listener
		menuButtonSettings.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(v.getContext(),
						SettingsPageActivity.class);
				startActivity(intent);
			}
		});
		
	}

	/**
	 * This method is responsible for populating the ListView with the appropriate views representative
	 * of todo items.
	 */
	private void populateTodoList() {

		DatabaseManager dbManager = new DatabaseManager();
		SQLiteDatabase db = dbManager.open(getApplicationContext());
		ToDoListManager todoListManager = new ToDoListManager(db);
		Cursor cursor = todoListManager
				.getAllTodoListItemsInCursorByUserId(TodoListAccount
						.getUserId());
		
		final ListView listView = this.getListView();
		
		final Spinner todoOptions = (Spinner) findViewById(R.id.invisibleSpinner);
		todoOptions.setOnItemSelectedListener(new todoOptionsListener());

		if (cursor != null) {
			startManagingCursor(cursor);
		}

		TextView displayMessage = (TextView) findViewById(R.id.todoListDisplayMessage);
		if (cursor == null || cursor.getCount() == 0) {
			displayMessage.setText("You currently have no Todo Items");
		} else {
			
			//create ArrayList of currently displayed todoItems
			for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
				TodoItem todoItem = new TodoItem();
				todoItem.setDescription(cursor.getString(cursor
						.getColumnIndex(DatabaseConstants.TODO_ITEM_TABLE_DESCRIPTION)));
				todoItem.setLatitude(cursor.getFloat(cursor
						.getColumnIndex(DatabaseConstants.TODO_ITEM_TABLE_LOCATION_LATITUDE)));
				todoItem.setLongitude(cursor.getFloat(cursor
						.getColumnIndex(DatabaseConstants.TODO_ITEM_TABLE_LOCATION_LONGITUDE)));
				todoItem.setAlarmRecurrenceType(cursor.getInt(cursor
						.getColumnIndex(DatabaseConstants.TODO_ITEM_TABLE_TODO_ALARM_RECURRENCE_TYPE)));
				todoItem.setPriorAlarmReminderTime(cursor.getLong(cursor
						.getColumnIndex(DatabaseConstants.TODO_ITEM_TABLE_TODO_PRIOR_ALARM_REMINDER_TIME)));
				todoItem.setTodoCompleted(cursor.getInt(cursor
						.getColumnIndex(DatabaseConstants.TODO_ITEM_TABLE_TODO_COMPLETED)));
				todoItem.setTodoItemCategoryCode(cursor.getInt(cursor
						.getColumnIndex(DatabaseConstants.TODO_ITEM_TABLE_CATEGORY_CODE)));
				todoItem.setTodoItemId(cursor.getLong(cursor
						.getColumnIndex(DatabaseConstants.ID)));
				todoItem.setTodoItemName(cursor.getString(cursor
						.getColumnIndex(DatabaseConstants.TODO_ITEM_TABLE_TODO_ITEM_NAME)));
				todoItem.setTodoTime(cursor.getLong(cursor
						.getColumnIndex(DatabaseConstants.TODO_ITEM_TABLE_TODO_TIME)));
				todoItem.setUserId(cursor.getLong(cursor
						.getColumnIndex(DatabaseConstants.TODO_ITEM_TABLE_USER_ID)));
	
				todoItemList.add(todoItem);
			}
			
			//populate list view
			String[] tableColumnNames = new String[] {
					DatabaseConstants.TODO_ITEM_TABLE_TODO_ITEM_NAME,
					DatabaseConstants.TODO_ITEM_TABLE_TODO_TIME };
			int[] textViewLabelNames = new int[] { R.id.todoTitle,
					R.id.todoDate };

			SimpleCursorAdapter notes = new SimpleCursorAdapter(this,
					R.layout.todo_item_row, cursor, tableColumnNames,
					textViewLabelNames);
			this.setListAdapter(notes);
			
		}

		listView.setOnItemClickListener(new OnItemClickListener() {
			
			//Occurs when a ListView item is clicked.
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			
				currentRowId = id;
				currentCheckBox = (ImageView) ((RelativeLayout)view).getChildAt(0);
				
				//set selection back to zero after each selection necessary to function properly
				todoOptions.setSelection(0,true);
				todoOptions.performClick();
		}
		});
		dbManager.close();

	}
	

	/**
	 * Responsible for responding when the user selects a value in the spinner that appears
	 * when a todo item is clicked 
	 * 
	 * @param The clicked view
	 */
	private class todoOptionsListener implements OnItemSelectedListener {
		

		@Override
		public void onNothingSelected(AdapterView<?> parent) {
			// do nothing
			
		}

		@Override
		public void onItemSelected(AdapterView<?> parent, View view, int pos,
				long id) {
			
			DatabaseManager dbManager = new DatabaseManager();
			SQLiteDatabase db = dbManager.open(getApplicationContext());
			ToDoListManager todoListManager = new ToDoListManager(db);
			TodoItem todoItem = todoListManager.getTodoListItemByTodoId(currentRowId);
			
			switch (pos) {
			//do nothing ("back" selected)
			//this is necessary b/c option 0 is automatically called when spinner created 
			case 0:
				break;
				
			//change state of check mark
			case 1:
				//if todo item is unchecked
				//TODO what about having some sort of image to allow the user to know the item has been checked or a custom toast or just setting the background of the button
				// to red for unchecked and green for checked... whatever works :P
				if(todoItem.getTodoCompleted()==0) {
					todoItem.setTodoCompleted(1);
					//update the database
					todoListManager.updateTodoListItemByTodoItemId(todoItem.getTodoItemId(),
							todoItem.getUserId(),todoItem.getTodoItemName(),
							todoItem.getTodoItemCategoryCode(), todoItem.getTodoTime(),
							todoItem.getLatitude(), todoItem.getLongitude(),
							todoItem.getDescription(), todoItem.getAlarmRecurrenceType(),
							todoItem.getPriorAlarmReminderTime(), 1);
					currentCheckBox.setImageResource(R.drawable.checked);
					Toast toast = Toast.makeText(getApplicationContext(), "Item set to Completed", Toast.LENGTH_SHORT);
					toast.show();
				}
				// if todo item is checked
				else {
					todoItem.setTodoCompleted(0);
					//update the database
					todoListManager.updateTodoListItemByTodoItemId(todoItem.getTodoItemId(),
							todoItem.getUserId(),todoItem.getTodoItemName(),
							todoItem.getTodoItemCategoryCode(), todoItem.getTodoTime(),
							todoItem.getLatitude(), todoItem.getLongitude(),
							todoItem.getDescription(), todoItem.getAlarmRecurrenceType(),
							todoItem.getPriorAlarmReminderTime(), 0);
					currentCheckBox.setImageResource(R.drawable.unchecked);
					Toast toast = Toast.makeText(getApplicationContext(), "Item set to Uncompleted", Toast.LENGTH_SHORT);
					toast.show();
				}
				break;
			
			// View Activity
			case 2:
				dbManager.close();
				Intent viewIntent = new Intent(view.getContext(), ViewTodoItemActivity.class);
				viewIntent.putExtra("ToDoItemLongId", currentRowId);
				startActivity(viewIntent);
				break;
			
			//Edit Activity
			case 3:
				dbManager.close();
				Intent editIntent = new Intent(view.getContext(), EditTodoItemActivity.class);
				editIntent.putExtra("ToDoItemLongId", currentRowId);
				startActivity(editIntent);
				break;
			
			//Delete
			case 4:
				todoListManager.deleteTodoListItemById(todoItem.getTodoItemId());
				break;
				
				
			}
			
			dbManager.close();
			populateTodoList();
			
		}
	}
}
